import React, { useEffect, useState, useRef } from 'react'
import { Button, Modal, Layout, Cascader, Avatar, message, List, Card, Descriptions, Input, Upload, Checkbox, Divider, Row, Col, Popover, Typography, Image } from 'antd';
import { } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom'
import axios from 'axios';
import { isOwnEmpty } from '../../../js/isEmptyObjc';
import myprovinceData from '../../../js/provinceData';
import moment from 'moment'
const provinceData = myprovinceData;
const CheckboxGroup = Checkbox.Group;
const { Title } = Typography;
const { TextArea } = Input;
export default function Index() {
  let editOrgInfo = {}
  const navigate = useNavigate()
  const [loginOrg, setLoginOrg] = useState(JSON.parse(localStorage.getItem("loginOrg")))
  const { Content, } = Layout;
  const [editvisible, seteditVisible] = useState(false);
  const [myId, setMyId] = useState(loginOrg.id);
  const [createNote, setcreateNote] = useState(false)
  const pwdRef = useRef();
  const nameRef = useRef();
  const addressRef = useRef();
  const phoneRef = useRef();
  const emailRef = useRef();
  const orgmsgRef = useRef();

  const titleRef = useRef();
  const msgref = useRef();
  const [file, setFile] = useState();

  const [orgNeedOptions2, setOrgNeedOptions2] = useState([]);//所有物资选项
  const [defaultCheckedList2, setDefaultCheckedList2] = useState([]);//默认选中(数据库中orgneed的need字段)
  const [checkedList2, setCheckedList2] = React.useState(defaultCheckedList2);
  const [orgNoticeList, setOrgNoticeList] = useState([]);
  useEffect(() => {
    message.destroy();

    axios.post("http://localhost:8080/qryGoods").then(resp => {
      console.log('goods表列表内容', resp);
      let goodslist = []
      for (let i = 0; i < resp.data.data.length; i++) {
        goodslist.push(resp.data.data[i].goodname)

      }
      console.log("goods表内所有物品:", goodslist);
      setOrgNeedOptions2(goodslist)
    })
    axios.post("http://localhost:8080/qryGoodsNeed?orgid=" + loginOrg.id).then(resp => {
      console.log("goodsneed表中这个org需要的物品有", resp);
      let goodsneedlist = []
      for (let i = 0; i < resp.data.data.length; i++) {
        goodsneedlist.push(resp.data.data[i].goodsname)
      }
      console.log("这个org需要的物品有", goodsneedlist);
      setDefaultCheckedList2(goodsneedlist)
      setCheckedList2(goodsneedlist)
    })
    axios.get("http://localhost:8080/qryOrgNoticeList?orgid=" + loginOrg.id).then(resp => {
      console.log("动态列表", resp);
      setOrgNoticeList(resp.data.data)
    })


    return () => {

    };
  }, []);
  const props = {
    onRemove: file => {
      setFile("")
    },
    beforeUpload: file => {
      setFile(file)
      return false;
    },
    file,
  };


  const checkBoxonChange = list => {
    setCheckedList2(list);
    console.log("改变后需要的物资有:", list);
  };

  const showModal = () => {
    seteditVisible(true);
    pwdRef.current.state.value = '';
    nameRef.current.state.value = '';
    addressRef.current.state.value = '';
    phoneRef.current.state.value = '';
    emailRef.current.state.value = '';
  };

  const handleOk = () => {
    editOrgInfo.password = pwdRef.current.state.value || null;
    editOrgInfo.orgname = nameRef.current.state.value || null;
    editOrgInfo.address = addressRef.current.state.value || null;
    editOrgInfo.phone = phoneRef.current.state.value || null;
    editOrgInfo.email = emailRef.current.state.value || null;

    editOrgInfo.orgmsg = orgmsgRef.current.resizableTextArea.textArea.value || null
    console.log("修改后机构信息:", editOrgInfo);
    console.log("空对象:", isOwnEmpty(editOrgInfo));
    if (isOwnEmpty(editOrgInfo)) {
      seteditVisible(false);
      return
    }
    editOrgInfo.id = myId;
    const emailreg = /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/;
    const phonereg = /^1[3|4|5|7|8]\d{9}$/
    const pwdReg = /^[a-zA-Z0-9]{6,18}$/;
    if (editOrgInfo.email != null) {
      if (!emailreg.test(editOrgInfo.email)) {
        message.error("邮箱格式错误!")
        seteditVisible(false);
        return
      }

    }
    if (editOrgInfo.phone != null) {
      if (!phonereg.test(editOrgInfo.phone)) {
        message.error("手机格式错误!")
        seteditVisible(false);
        return
      }

    }
    if (editOrgInfo.password != null) {
      if (!pwdReg.test(editOrgInfo.password)) {
        message.error("密码为6-18位数字字母组合!")
        seteditVisible(false);
        return
      }
    }
    axios.post("http://localhost:8080/editOrg", editOrgInfo).then(resp => {
      if (resp.data.state === "0") {
        message.success(resp.data.message, 1)
        setTimeout(() => {
          window.location.reload();
          seteditVisible(false);
        }, 1000);

      } else {
        message.error(resp.data.message, 1)
      }

    }).catch(err => {
      message.error("请求超时!", 1);
      setTimeout(() => {
        navigate('/menu/donation/*')
        seteditVisible(false);
      }, 1000);

    })

  };



  const citySelect = (value) => {
    let cityStr = ""
    for (const v of value) {
      cityStr += v;
    }

    console.log(cityStr);
    editOrgInfo.city = cityStr;
  }

  const handleCancel = () => {
    seteditVisible(false);
    editOrgInfo = {}
  };
  const photoupdate = (info) => {
    if (info.file.status !== 'uploading') {
      console.log(info.file, info.fileList);
    }
    if (info.file.status === 'done') {
      message.success(`${info.file.name} 更换成功`);
      setTimeout(() => {
        window.location.reload()
      }, 500);
    } else if (info.file.status === 'error') {
      message.error(`${info.file.name} 网络异常.`);
    }

  }
  const beforeUpload = (file) => {
    console.log(file.size);
    if (file.size > (2097152)) {
      console.log("图片超过2M");
      message.error(`图片不得超过2M`);
      return Upload.LIST_IGNORE;
    } else {
      return true;
    }
  }

  const saveOrgNeed2 = () => {
    let goodsneedrs = {};
    goodsneedrs.orgid = loginOrg.id;
    goodsneedrs.newgoodsneed = checkedList2;
    console.log(goodsneedrs);
    axios.post("http://localhost:8080/updategoodsneed", goodsneedrs).then(resp => {
      console.log(resp);
      message.success("操作成功!", 1)
      setTimeout(() => {

        window.location.reload();
      }, 500);
    })
  }

  const createNoteOK = async () => {
    if (titleRef.current.state.value == undefined) {
      message.error("请输入标题", 1)
      return
    }
    if (msgref.current.resizableTextArea.textArea.value == undefined || msgref.current.resizableTextArea.textArea.value == "") {
      message.error("请输入正文内容", 1)
      return
    }

    if (file == null || file == "") {
      message.error("请上传一张图片", 1)
      return
    }
    let params = new FormData();
    params.append("title", titleRef.current.state.value)
    params.append("orgid", loginOrg.id)
    params.append("msg", msgref.current.resizableTextArea.textArea.value)
    params.append("file", file)

    const resp = await axios.post("http://localhost:8080/createOrgNotice", params)
    if (resp.data.state == "0") {
      message.success(resp.data.message);
      setTimeout(() => {
        window.location.reload()
      }, 500);

    } else {
      message.error(resp.data.message);
    }
  }

  return (
    <Content style={{ padding: 15, backgroundColor: '#FFF' }} >
      <Row>
        <Col>
          <Title level={3}>机构资料</Title>
        </Col>

      </Row>

      <Row justify="center">
        <Col>
          <Popover placement="topLeft" content={'点击修改头像'}>
            <Upload maxCount={1} action={`http://localhost:8080/saveUserHead?id=${myId}`} onChange={photoupdate} beforeUpload={beforeUpload}>
              <Avatar src={`http://localhost:8080/getOrgHead?id=${myId}`} alt='机构头像' size={100} />
            </Upload>
          </Popover>
        </Col>
      </Row>
      <Row justify="center" style={{ marginTop: '0.3REM' }}>
        <Col>
          <Descriptions bordered column={{ xxl: 4, xl: 3, lg: 3, md: 3, sm: 2, xs: 1 }} size="middle " >
            <Descriptions.Item label="机构名称">{loginOrg.orgname}</Descriptions.Item>
            <Descriptions.Item label="所在城市">{loginOrg.city || "-"}</Descriptions.Item>
            <Descriptions.Item label="详细地址">{loginOrg.address || "-"}</Descriptions.Item>
            <Descriptions.Item label="邮箱">{loginOrg.email || "-"}</Descriptions.Item>
            <Descriptions.Item label="联系电话">{loginOrg.phone || "-"}</Descriptions.Item>
            <Descriptions.Item label="机构介绍">{loginOrg.orgmsg || "-"}</Descriptions.Item>
            <Descriptions.Item label="累计积分">{loginOrg.point || "-"}</Descriptions.Item>
            <Descriptions.Item label="操作">
              <Row justify="space-around" gutter={8}>
                <Col><Button size="small" type="primary" onClick={showModal}>修改信息</Button></Col>

                {/* <Col><Button size="small" type="primary" onClick={createOrgNotice}>发布动态</Button></Col> */}
                <Col><Button size="small" type="primary" onClick={() => { setcreateNote(true) }}>发布动态</Button></Col>
              </Row>

            </Descriptions.Item>
          </Descriptions>
        </Col>
        <Divider />
      </Row>
      <Row>
        <Col>
          <Title level={3}>物资需求</Title>
        </Col>

      </Row>
      <Row>
        <Col xl={20}>
          <CheckboxGroup options={orgNeedOptions2} value={checkedList2} onChange={checkBoxonChange} />
        </Col>
        <Col xl={4}>
          <Button type="primary" onClick={saveOrgNeed2}>保存需求</Button>
        </Col>
      </Row>
      <Divider />

      <Row>
        <Col>
          <Title level={3}>最近动态</Title>
        </Col>

      </Row>
      <List
        itemLayout="vertical"
        size="small"
        pagination={{
          pageSize: 2,
        }}
        dataSource={orgNoticeList}
        renderItem={item => (
          <List.Item
            key={item.title}
            extra={
              <Image
                width={220}
                height={180}
                alt="logo"
                src={"http://localhost:8080/getNoticePhoto?id=" + item.id}
              />
            }
          >
            <List.Item.Meta
              avatar={<Avatar src={`http://localhost:8080/getOrgHead?id=${loginOrg.id}`} />}
              title={item.title}
              description={moment(Number(item.createtime)).format('YYYY-MM-DD HH:mm:ss')}
            />
            {item.msg}
          </List.Item>
        )}
      />

      <Modal
        title="编辑资料"
        visible={editvisible}
        onOk={handleOk}
        onCancel={handleCancel}
        centered={true}
      >
        <Row justify="center">
          <Col>
            <Input type={"password"} placeholder="密码" style={{ width: '1.7REM', marginTop: '0.03REM' }} ref={pwdRef} />
          </Col>
        </Row>
        <Row justify="center">
          <Col>
            <Input placeholder="机构名称" style={{ width: '1.7REM', marginTop: '0.03REM' }} ref={nameRef} />
          </Col>
        </Row>
        <Row justify="center">
          <Col>
            <Input placeholder="地址" style={{ width: '1.7REM', marginTop: '0.03REM' }} ref={addressRef} />
          </Col>
        </Row>
        <Row justify="center">
          <Col>
            <Input placeholder="联系电话" style={{ width: '1.7REM', marginTop: '0.03REM' }} ref={phoneRef} />
          </Col>
        </Row>
        <Row justify="center">
          <Col>
            <Input placeholder="邮箱" style={{ width: '1.7REM', marginTop: '0.03REM' }} ref={emailRef} />
          </Col>
        </Row>
        <Row justify="center">
          <Col>
            <Cascader placeholder="城市" style={{ width: '1.7REM', marginTop: '0.03REM' }} onChange={citySelect} options={provinceData} defaultValue={''} />
          </Col>
        </Row>
        <Row justify="center">
          <Col>
            <Input.TextArea placeholder="机构介绍" style={{ width: '1.7REM', marginTop: '0.03REM' }} ref={orgmsgRef} />
          </Col>
        </Row>


      </Modal>

      <Modal
        title="发布动态"
        visible={createNote}
        onOk={createNoteOK}
        onCancel={() => { setcreateNote(false) }}
        centered={true}
      >
        <Row justify="center">
          <Col>
            <Input placeholder="输入标题" ref={titleRef} style={{ width: '1.7REM', marginTop: '0.03REM' }} />
          </Col>
        </Row>
        <Row justify="center">
          <Col>
            <TextArea placeholder="输入正文" ref={msgref} style={{ width: '1.7REM', marginTop: '0.03REM' }} />
          </Col>
        </Row>
        <Row justify="center">
          <Col>
            <Upload maxCount={1} {...props} onChange={photoupdate} style={{ width: '1.7REM', marginTop: '0.03REM' }}>
              <Button style={{ width: '100%' }}>上传图片</Button>
            </Upload>
          </Col>
        </Row>


      </Modal>
    </Content>
  )

}
